package com.yz.jdd.base.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.media.SoundPool;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import androidx.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.yz.jdd.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;

/**
 * Created by shibin on 2016/12/25.
 */
public class Tools {
    private static Toast toast;


    /**
     * 获取数字文件map
     *
     * @param soundPool
     * @param activity
     * @return
     */
    public static Map<Integer, Integer> getSoundMap(SoundPool soundPool, Activity activity) {
        Map<Integer, Integer> soundMap = new HashMap<>(13);
        soundMap.put(0, soundPool.load(activity, R.raw.yz_0, 1));
        soundMap.put(1, soundPool.load(activity, R.raw.yz_1, 1));
        soundMap.put(2, soundPool.load(activity, R.raw.yz_2, 1));
        soundMap.put(3, soundPool.load(activity, R.raw.yz_3, 1));
        soundMap.put(4, soundPool.load(activity, R.raw.yz_4, 1));
        soundMap.put(5, soundPool.load(activity, R.raw.yz_5, 1));
        soundMap.put(6, soundPool.load(activity, R.raw.yz_6, 1));
        soundMap.put(7, soundPool.load(activity, R.raw.yz_7, 1));
        soundMap.put(8, soundPool.load(activity, R.raw.yz_8, 1));
        soundMap.put(9, soundPool.load(activity, R.raw.yz_9, 1));
        soundMap.put(10, soundPool.load(activity, R.raw.yz_dot, 1));
        soundMap.put(11, soundPool.load(activity, R.raw.yz_click, 1));
        soundMap.put(12, soundPool.load(activity, R.raw.yz_add, 1));
        return soundMap;
    }

    /**
     * 播放数字按键声音
     *
     * @param soundMap
     * @param soundPool
     * @param code      数字键  0 1 2 3 4 5 6 7 8 9 . click add 00
     */
    public static void soundMapPlay(Map<Integer, Integer> soundMap, SoundPool soundPool, String code) {
        switch (code) {
            case "0":
                soundPool.play(soundMap.get(0), 1, 1, 1, 0, 1);
                break;
            case "1":
                soundPool.play(soundMap.get(1), 1, 1, 1, 0, 1);
                break;
            case "2":
                soundPool.play(soundMap.get(2), 1, 1, 1, 0, 1);
                break;
            case "3":
                soundPool.play(soundMap.get(3), 1, 1, 1, 0, 1);
                break;
            case "4":
                soundPool.play(soundMap.get(4), 1, 1, 1, 0, 1);
                break;
            case "5":
                soundPool.play(soundMap.get(5), 1, 1, 1, 0, 1);
                break;
            case "6":
                soundPool.play(soundMap.get(6), 1, 1, 1, 0, 1);
                break;
            case "7":
                soundPool.play(soundMap.get(7), 1, 1, 1, 0, 1);
                break;
            case "8":
                soundPool.play(soundMap.get(8), 1, 1, 1, 0, 1);
                break;
            case "9":
                soundPool.play(soundMap.get(9), 1, 1, 1, 0, 1);
                break;
            case ".":
                soundPool.play(soundMap.get(10), 1, 1, 1, 0, 1);
                break;
            case "click":
                soundPool.play(soundMap.get(11), 1, 1, 1, 0, 1);
                break;
            case "add":
                soundPool.play(soundMap.get(12), 1, 1, 1, 0, 1);
                break;
            default:
                break;
        }

    }


    public static void showToast(Context context, String str) {
        showToast(context, str, Toast.LENGTH_SHORT);
    }

    public static void showToast(Context context, String str, int duration) {
        if (toast == null) {
            toast = Toast.makeText(context.getApplicationContext(), str, duration);
        } else {
            toast.setText(str);
            toast.setDuration(duration);
        }
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static StateListDrawable setSelector(Context context, int normalId, int pressId) {
        StateListDrawable bg = new StateListDrawable();
        Drawable idNormal = context.getResources().getDrawable(normalId);
        Drawable idPressed = context.getResources().getDrawable(pressId);
        bg.addState(new int[]{android.R.attr.state_selected, -android.R.attr.state_pressed},
                idPressed);
        bg.addState(new int[]{-android.R.attr.state_focused}, idNormal);
        //bg.addState(new int[] {}, idNormal);
        return bg;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public static void hideKeyboard(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context
                .INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        //显示键盘
        //imm.showSoftInput(editText,0);
        //隐藏键盘
        //imm.hideSoftInputFromWindow(editText.getWindowToken(),0);
    }

    public static String getSafeString(String value) {
        return getSafeString(value, "");
    }

    public static String getSafeString(String value, String defaultVal) {
        return TextUtils.isEmpty(value) ? defaultVal : value;
    }

    public static int getSafeInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            return 0;
        }
    }

    public static float getSafeFloat(String value) {
        try {
            return Float.parseFloat(value);
        } catch (Exception e) {
            return 0.0f;
        }

    }

    //判断输入的是否为非0正整数 是返回true
    public static boolean isIntNumber(String str) {
        String regex = "^[0-9]\\d*";
        return str.matches(regex);
    }

    /**
     * 设置边框颜色
     *
     * @param view
     * @param type 1-标红 0-置灰
     */
    public static void setShapeBorderColor(View view, int type) {
        GradientDrawable myGrad = (GradientDrawable) view.getBackground();
        if (1 == type)
            myGrad.setStroke(1, Color.parseColor("#ea4242"));
        else
            myGrad.setStroke(1, Color.parseColor("#ececec"));
    }

    public static int getScreenWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeight(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /**
     * 状态栏相关工具类
     */

    public static void setWindowStatusBarColor(Activity activity, int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = activity.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(activity.getResources().getColor(colorResId));

                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SpannableStringBuilder getSpnnableString(String content, int textSize) {
        //SpannableString ss = new SpannableString(content);
        SpannableStringBuilder ss = new SpannableStringBuilder(content);
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(textSize, true);
        ss.setSpan(new StyleSpan(Typeface.NORMAL), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }

    public static int getStatusBarHeight(Activity activity) {
        int status_bar_height = 20;
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            status_bar_height = activity.getResources().getDimensionPixelSize(resourceId);
        }
        return status_bar_height;
    }

    public static String getDate() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyMMdd");
        return sDateFormat.format(new java.util.Date());
    }

    public static String getTime() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("hhmmss");
        return sDateFormat.format(new java.util.Date());
    }

    public static String getCurrentTime() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sDateFormat.format(System.currentTimeMillis());
    }

    public static HashMap<String, Object> Obj2Map(Object obj) {
        HashMap<String, Object> map = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                map.put(field.getName(), field.get(obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }


    public static String getDeviceInfo() {
        return Build.BRAND;
    }


    public static int getWidth(Context context) {
        WindowManager wm = ((Activity) context).getWindowManager();
        return wm.getDefaultDisplay().getWidth();
    }

    public static int getHeight(Context context) {
        WindowManager wm = ((Activity) context).getWindowManager();
        return wm.getDefaultDisplay().getHeight();
    }

    /**
     * 日期比较
     *
     * @param DATE1
     * @param DATE2
     * @return
     */

    public static int compare_date(String DATE1, String DATE2) {


        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * @param str 判断输入的是否是正则中的内容
     * @return
     */
    public static boolean isUSERNAME(String str) {
        String matchFilter = "[0-9a-zA-Z\u4e00-\u9fa5]+";
        Pattern pattern = Pattern.compile(matchFilter);
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 退款原因过滤特殊字符
     */
    public static boolean filterRefundReason(String str) throws PatternSyntaxException {
        String regEx = "[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param splitStr 截取字符串返回List
     * @return
     */
    public static List<String> splitList(String splitStr) {
        List<String> list = new ArrayList<String>();
        if (!TextUtils.isEmpty(splitStr)) {
            try {
                list = Arrays.asList(splitStr.split("--"));
            } catch (Exception e) {
                return list;
            }
        }
        return list;
    }

    /**
     * @param str1 时间段的开始
     * @param str2 时间段的结束
     * @return 输入的两个Date类型数据之间的时间间格用* days * hours * minutes * seconds的格式展示
     * @author fy.zhang
     */
    public static long getDistanceDays(String str1, String str2) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date one;
        Date two;
        long days = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff;
            if (time1 < time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            days = diff / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 获取当前日期
     *
     * @return
     */
    public static String getNowDate() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Calendar cd = Calendar.getInstance();
            return sdf.format(cd.getTime());

        } catch (Exception e) {
            return "";
        }
    }

    public static Observable<Integer> countdown(int time) {
        if (time < 0) time = 0;

        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1);

    }

    //md5校验
    private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * Get MD5 of a file (lower case)
     * @return empty string if I/O error when get MD5
     */
    @NonNull
    public static String getFileMD5(@NonNull File file) {

        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            FileChannel ch = in.getChannel();
            return MD5(ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length()));
        } catch (FileNotFoundException e) {
            return "";
        } catch (IOException e) {
            return "";
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // 关闭流产生的错误一般都可以忽略
                }
            }
        }

    }

    /**
     * MD5校验字符串
     * @param s String to be MD5
     * @return 'null' if cannot get MessageDigest
     */
    @NonNull
    private static String getStringMD5(@NonNull String s) {
        MessageDigest mdInst;
        try {
            // 获得MD5摘要算法的 MessageDigest 对象
            mdInst = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }

        byte[] btInput = s.getBytes();
        // 使用指定的字节更新摘要
        mdInst.update(btInput);
        // 获得密文
        byte[] md = mdInst.digest();
        // 把密文转换成十六进制的字符串形式
        int length = md.length;
        char str[] = new char[length * 2];
        int k = 0;
        for (byte b : md) {
            str[k++] = hexDigits[b >>> 4 & 0xf];
            str[k++] = hexDigits[b & 0xf];
        }
        return new String(str);
    }

    @NonNull
    private static String getSubStr(@NonNull String str, int subNu, char replace) {
        int length = str.length();
        if (length > subNu) {
            str = str.substring(length - subNu, length);
        } else if (length < subNu) {
            // NOTE: padding字符填充在字符串的右侧，和服务器的算法是一致的
            str += createPaddingString(subNu - length, replace);
        }
        return str;
    }

    @NonNull
    private static String createPaddingString(int n, char pad) {
        if (n <= 0) {
            return "";
        }

        char[] paddingArray = new char[n];
        Arrays.fill(paddingArray, pad);
        return new String(paddingArray);
    }

    /**
     * 计算MD5校验
     * @param buffer
     * @return 空串，如果无法获得 MessageDigest实例
     */
    @NonNull
    private static String MD5(ByteBuffer buffer) {
        String s = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(buffer);
            byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
            // 用字节表示就是 16 个字节
            char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
            // 所以表示成 16 进制需要 32 个字符
            int k = 0; // 表示转换结果中对应的字符位置
            for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
                // 转换成 16 进制字符的转换
                byte byte0 = tmp[i]; // 取第 i 个字节
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>>,
                // 逻辑右移，将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
            }
            s = new String(str); // 换后的结果转换为字符串

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 判断字符串中是否包含中文
     * @param str
     * 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 判断网络是否可用
     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
     *
     * @param context 上下文
     * @return {@code true}: 可用<br>{@code false}: 不可用
     */
    public static boolean isNetAvailable(Context context) {
        NetworkInfo info = getActiveNetworkInfo(context);
        return info != null && info.isAvailable();
    }
    /**
     * 获取活动网络信息
     *
     * @param context 上下文
     * @return NetworkInfo
     */
    public static NetworkInfo getActiveNetworkInfo(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }
    /**
     * 小数位是0的 直接取整。
     *
     * @param decimal
     * @return
     */
    public static String decimalZeroRoundness(String decimal) {
        decimal = decimal.replace(",", "");
        Double floatReceipt = Double.parseDouble(decimal);
        //判断是否符合取整条件
        if (floatReceipt.intValue() - floatReceipt == 0) {
            return String.valueOf(floatReceipt.intValue());
        } else {
            return String.valueOf(floatReceipt);
        }

    }
}
